// Package models
// @Title  roleModel.go
// @Description  角色模型
// @Author  小斌 (时间 格式是2021/12/02  10:20)
// @Update  小斌 (时间 格式是2021/12/02  10:20)

package models

import (
	"github.com/astaxie/beego/orm"
	"time"
)

// RoleObj 用户角色 实体类
type RoleObj struct {
	Id                 int    `valid:"id"`
	RoleName               string `valid:"role_name"`
	Desc                string `valid:"desc"`
	Auth                string `valid:"auth"`
	IsDelete				int `valid:"is_delete"`
	UpdateTime                time.Time `valid:"update_time" orm:"auto_now"`
	AddTime                time.Time `valid:"add_time" orm:"auto_now_add"`

}

func (this *RoleObj) TableName() string {
	return "role"
}

func init() {
	orm.RegisterModel(new(RoleObj))
}

// GetRoleList 获取分页数据
func GetRoleList(pageSize, page int) (*[]RoleObj, int, error) {
	var (
		list []RoleObj
		err  error
	)
	qs := orm.NewOrm().QueryTable(new(RoleObj)).OrderBy("-add_time")

	_, err = qs.Filter("is_delete",0).Limit(pageSize).Offset((page - 1) * pageSize).RelatedSel().All(&list)
	count, _ := qs.Count()
	if err == orm.ErrNoRows || err == orm.ErrMissPK {
		return nil, 0, err
	}

	return &list, int(count), nil
}

// GetRoleInfoById 根据id获取记录
func GetRoleInfoById(id int) (RoleObj,error) {
	var (
		row RoleObj
		err  error
	)

	err = orm.NewOrm().QueryTable(new(RoleObj)).Filter("id", id).Filter("is_delete", 0).One(&row)
	if err == orm.ErrNoRows || err == orm.ErrMissPK {
		return row,nil
	}

	return row,nil
}


// AddRole 添加角色
func AddRole(roleName string,desc string,auth string) int64 {
	role := RoleObj{
		RoleName:    roleName,
		Desc:  desc,
		IsDelete: 0,
		Auth : auth,
	}
	id,err := orm.NewOrm().Insert(&role)
	if err == orm.ErrNoRows || err == orm.ErrMissPK {
		return 0
	}

	return id
}

// UpdateRoleById 修改角色
func UpdateRoleById(id int,roleName string,desc string,auth string) int64 {
	role := RoleObj{
		Id :    id,
		RoleName : roleName,
		Desc : desc,
		Auth : auth,
	}

	num,err := orm.NewOrm().Update(&role,"role_name","desc","auth")
	if err == orm.ErrNoRows || err == orm.ErrMissPK {
		return 0
	}

	return num
}

// DeleteRoleById 删除管理员
func DeleteRoleById(id int) int64 {
	role := RoleObj{
		Id:    id,
		IsDelete: 1,
	}
	num,err := orm.NewOrm().Update(&role,"is_delete")
	if err == orm.ErrNoRows || err == orm.ErrMissPK {
		return 0
	}

	return num
}